import logging
import math
from re import search
from typing import Optional, List

from fastapi import APIRouter, Depends, Query, Path
from pydantic import Field, BaseModel
from sqlalchemy import text
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session
from commons.BaseResponse import BaseResponse
from commons.PaginationBase import PaginationBase
from datebase import get_db
from utils.EncryptionUtil import oauth2_scheme, EncryptionMiddleware

task_user_router = APIRouter(prefix="/tsTaskuser", tags=["课题组人员资料管理"], dependencies=[Depends(oauth2_scheme)])


class ResearchGroupPersonnelSearch(PaginationBase):
    ftaskno: str = Field(..., description="任务编号")


@task_user_router.get("/list", summary="课题组人员资料查询接口")
def list_task_user(search: ResearchGroupPersonnelSearch = Query(), db: Session = Depends(get_db)):
    param = {"ftaskno": search.ftaskno}
    sql = "select count(1) from m_ts_taskuser a,am_sys_user b"
    sql = sql + " where 1=1"
    sql = sql + " and ftaskno = :ftaskno "
    sql = sql + " and a.fuserno=cast(b.id as varchar)"
    sql = sql + " order by  b.id "
    count = db.execute(text(sql), param).scalar()

    param = {"ftaskno": search.ftaskno}
    sql = "select b.id,b.username"
    sql = sql + " from m_ts_taskuser a,am_sys_user b"
    sql = sql + " where 1=1"
    sql = sql + " and ftaskno = :ftaskno "
    sql = sql + " and a.fuserno=cast(b.id as varchar)"
    sql = sql + " order by  b.id "
    sql = sql + " limit :limit offset :offset "
    param["offset"] = search.offset
    param["limit"] = search.limit
    data = db.execute(text(sql), param).fetchall()
    data_list = []
    for key in range(len(data)):
        d1 = {}
        d1['id'] = data[key][0]
        d1['username'] = data[key][1]
        data_list.append(d1)

    info_dict = {"list": data_list,
                 "limit": search.limit,
                 "page": search.pageIndex,
                 "pages": (count + search.limit - 1) // search.limit,
                 "total": count}
    return BaseResponse.success(data=info_dict)


@task_user_router.post("/delete/{taskno}/{userno}", summary="课题组人员删除接口")
def delete_task_user(taskno: str = Path(description="任务编号"), userno: str = Path(description="用户编号"),
                     db: Session = Depends(get_db)):
    try:
        with db.begin():
            sql = "delete from m_ts_taskuser where ftaskno= :taskno and fuserno= :userno "
            db.execute(text(sql), {"taskno": taskno, "userno": userno})
            return BaseResponse.success()
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")


class ResearchGroupPersonnelCreate(BaseModel):
    """课题组人员新增请求参数"""
    ftaskno: str = Field(..., description="任务编号")
    fuserno: str = Field(..., description="用户编号")


@task_user_router.post("/create", summary="课题组人员新增接口")
def create_task_user(create: ResearchGroupPersonnelCreate, db: Session = Depends(get_db)):
    try:
        with db.begin():
            sql = "select ftaskno from m_ts_taskuser where ftaskno= :ftaskno  and fuserno= :fuserno "
            data = db.execute(text(sql), {
                "ftaskno": create.ftaskno,
                "fuserno": create.fuserno,
            }).fetchall()
            if len(data) > 0:
                return BaseResponse.error(message="课题组人员已存在")
            else:
                sql = "insert into m_ts_taskuser(ftaskno,fuserno)"
                sql = sql + " values( :ftaskno , :fuserno );"
                db.execute(text(sql), {
                    "ftaskno": create.ftaskno,
                    "fuserno": create.fuserno,
                })
                # 返回
                d1 = {}
                d1["ftaskno"] = create.ftaskno
                d1["fuserno"] = create.fuserno
                return BaseResponse.success(data=d1)
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
